import os

from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
from bs4 import BeautifulSoup
import time


class Label(models.Model):
    title = models.CharField('标题', max_length=10)

    def __str__(self):
        return self.title


# Create your models here.
class Blog(models.Model):
    title = models.CharField('标题', max_length=200)
    image = models.ImageField('主题图片', blank=True)
    pub_date = models.DateTimeField('发布时间', auto_now_add=True)
    last_update_date = models.DateTimeField('最后更新时间', auto_now=True)
    content = models.TextField('内容', blank=True, null=True, default="")
    html = models.TextField('渲染页面', blank=True, null="", default="")
    browse_times = models.IntegerField('浏览次数', default=0)
    labels = models.ManyToManyField(Label, verbose_name='标签')
    creator = models.ForeignKey(User, verbose_name='发布者', on_delete=models.DO_NOTHING)
    richText = RichTextUploadingField("博客内容", null=True, blank=True, default="")

    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.title

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=False):
        if (self.richText != "") and (self.richText is not None):
            soup = BeautifulSoup(self.richText, "html.parser")
            image_list = soup.find_all('img')
            for img in image_list:
                img_str = img['src']
                if (img_str.find("www.xn--sxrs6nf68c.xn--6qq986b3xl") == -1) and (img_str.find("127.0.0.1") == -1):
                    img['src'] = 'https://www.xn--sxrs6nf68c.xn--6qq986b3xl:8000/' + img_str
            self.richText = str(soup)
        super(Blog, self).save()


class Picture(models.Model):
    def upload_to(self, filename):
        if filename is None:
            filename = time.strftime("%HH-%mm-%ss", time.localtime())
        now_year_month = time.strftime("%Y-%m", time.localtime())
        url = now_year_month + os.path.sep + str(self.blogId_id) + os.path.sep + filename
        self.url = settings.MEDIA_URL + url
        return url

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if self.title == '':
            self.title = "".join(self.image.name.split('.')[:-1])
        super(Picture, self).save()

    blogId = models.ForeignKey(Blog, verbose_name='博客', related_name='blog_id', on_delete=models.DO_NOTHING)
    title = models.CharField('图片名称', blank=True, max_length=100)
    image = models.ImageField('图片', upload_to=upload_to, blank=False)
    url = models.CharField('访问链接', blank=True, max_length=100)
    pub_date = models.DateTimeField('发布时间', auto_now_add=True)

    def __str__(self):
        return self.title
